package com.hhss.qishi.config.exception;

import com.alibaba.fastjson.JSON;
import com.hhss.qishi.config.log.Log;
import com.hhss.qishi.entity.system.OutputResult;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;

@RestControllerAdvice
public class GlobalExceptionHandler {

	@Log
	Logger log;

	@Autowired
	PropertiesManager manager;

	private OutputResult result = new OutputResult();
	
	@ExceptionHandler(Exception.class)
	public String handlerException(Exception e) {

		// 如果是自定义的异常，返回对应的错误信息
		if (e instanceof UniteException) {
			e.printStackTrace();
			UniteException exception = (UniteException) e;
			String code = exception.getMessage();
			String msg = manager.getMsg(code);

			if (!StringUtils.isEmpty(msg)) {
				result.setReturnCode(code);
				result.setReturnMsg(MessageFormat.format(msg, exception.getArgs()));
			} else {
				result.setReturnCode(ExceptionMsg.EXCEPTION_UNKNOWN);
				result.setReturnMsg(manager.getMsg(ExceptionMsg.EXCEPTION_UNKNOWN));
			}
		} if(e instanceof AccessDeniedException) {
			result.setReturnCode(ExceptionMsg.EXCEPTION_NO_PERMISSION);
			result.setReturnMsg(manager.getMsg(ExceptionMsg.EXCEPTION_NO_PERMISSION));
		} else{
			// 如果不是已知异常，返回系统异常
			log.info(e.getMessage());
			e.printStackTrace();
			result.setReturnCode(ExceptionMsg.EXCEPTION_UNKNOWN);
			result.setReturnMsg(manager.getMsg(ExceptionMsg.EXCEPTION_UNKNOWN));
		}
		return JSON.toJSONString(result);
	}

}